package test.solon.config;

import cn.hutool.core.io.IoUtil;
import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;
import org.apache.ibatis.session.SqlSessionFactory;
import org.noear.solon.annotation.Bean;
import org.noear.solon.annotation.Configuration;
import org.noear.solon.annotation.Inject;
import test.solon.mapper.UserMapper;
import top.lingkang.mm.MagicConfiguration;
import top.lingkang.mm.gen.DefaultIdGenerate;
import top.lingkang.mm.orm.MapperManage;
import top.lingkang.mm.solon.SolonMapperManage;

import javax.sql.DataSource;
import java.io.InputStream;

/**
 * @author lingkang
 * Created by 2024/2/28
 */
@Configuration
public class AppConfig {
    @Bean
    public DataSource dataSource() {
        HikariConfig config = new HikariConfig();
        config.setDriverClassName("org.h2.Driver");
        config.setJdbcUrl("jdbc:h2:mem:mybatismagicdb");
        config.setUsername("root");
        config.setPassword("123456");
        config.setMaximumPoolSize(3);
        HikariDataSource dataSource = new HikariDataSource(config);
        return dataSource;
    }

    @Bean
    public SqlSessionFactory sqlSessionFactory(@Inject DataSource dataSource) {
        MagicConfiguration magicConfiguration = new MagicConfiguration(dataSource);
        magicConfiguration.setMapUnderscoreToCamelCase(true);// 下划线转驼峰
        // 或 xml 文件加载`configuration.addMapperXml("mapper/UserMapper.xml");`
        magicConfiguration.addMapperXml("mapper"); // resources/mapper/UserMapper.xml

        /*
        // 执行初始化sql脚本，若需要执行的话
        Connection connection = sqlSession.getConnection();
        String script = IoUtil.read(getClass().getClassLoader().getResourceAsStream("script/init-mysql.sql"), StandardCharsets.UTF_8);
        MagicUtils.exeScript(script, connection);
        */

        SqlSessionFactory sqlSessionFactory = magicConfiguration.build();
        return sqlSessionFactory;
    }

    @Bean
    public MapperManage mapperManage(@Inject SqlSessionFactory sqlSessionFactory) {
        SolonMapperManage manage = new SolonMapperManage(
                sqlSessionFactory.getConfiguration(),
                sqlSessionFactory.openSession());
        manage.setIdGenerate(new DefaultIdGenerate());
        InputStream stream = AppConfig.class.getClassLoader().getResourceAsStream("sql/init-h2.sql");
        String sql = IoUtil.readUtf8(stream);
        System.out.println("开始执行SQL");
        manage.executeSqlScript(sql);
        System.out.println("SQL执行完毕");
        return manage;
    }
}
